package org.diy.traffic.util;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Class to handle logging
 * 
 * TODO This should be refactored to actually use Java's built-in logging features!!
 * @author Dan Greenblatt
 *
 */
public class TLog {

    private static String logFile = "./diydata.log";
    private static Logger myLogger = Logger.getAnonymousLogger();
    
    private final static DateFormat df = new SimpleDateFormat ("yyyy.MM.dd  hh:mm:ss ");
    
    private static Level thresholdLevel= Level.INFO; //700
    
    private static FileWriter myFileWriter = null;
    
    private TLog() { }
    	
    public static void setLogThreshold(Level l) {
    	thresholdLevel = l;
    }
    
	public static void log(Level level, String msg) {
		if (level.intValue() >= thresholdLevel.intValue()) {
			write(msg);
		}
	}
	
	public static void log(Level level, Exception e) {
		if (level.intValue() >= thresholdLevel.intValue()) {
			write(e);
		}
	}
	
    public static void setLogFilename(String filename) {
        logFile = filename;

        new File(filename).delete();
        
        try {
			myFileWriter = new FileWriter(filename, true);
		} catch (IOException e) {
            System.out.println(stack2string(e));
		}
    }
    
    public static void write(String msg) {
        write(logFile, msg);
    }
    
    public static void write(Exception e) {
        write(logFile, stack2string(e));
    }

    public static void write(String file, String msg) {
        try {
            Date now = new Date();
            String currentTime = TLog.df.format(now); 
            if (myFileWriter != null) {
            	myFileWriter.write(currentTime + " " + msg 
            			+ System.getProperty("line.separator"));
            	System.out.println(currentTime + " " + msg);
            	myFileWriter.flush();
            	//myFileWriter.close();
            }
        }
        catch (Exception e) {
            System.out.println(stack2string(e));
        }
    }
    
    private static String stack2string(Exception e) {
        try {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            return "------\r\n" + sw.toString() + "------\r\n";
        }
        catch(Exception e2) {
            return "bad stack2string";
        }
    }
}

